package com.rs.qm.modules.member.controller;

import com.aliyuncs.exceptions.ClientException;
import com.rs.qm.common.utils.*;
import com.rs.qm.modules.sys.service.SysCaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 用户注册发送验证码
 */
@RestController
@Slf4j
@Transactional
public class ValidateCodeController {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    @GetMapping("/pc/sandsms/{telephone}/{jpgCode}")
    public R sandSms(@PathVariable String telephone, @PathVariable String jpgCode) {
        //获取随机验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        String validateCode = code.toString();
        //redis保存的图形验证码
        String redis_JPGCode = redisUtils.get(telephone + RedisMessageConstant.SENDTYPE_JPG);
        //redis保存的发送短信的次数
        String key_Count = telephone + RedisMessageConstant.SENDTYPE_COUNT;
        String val_count = redisUtils.get(key_Count);
        //判断发送短信的次数是否大于等于两次
        if (val_count != null && Integer.parseInt(val_count) >= 3) {
            if(StringUtil.isEmpty(jpgCode) || "null".equals(jpgCode)){
                return R.error(20001,"超过2次,请输入图形验证码!");
            }
            //大于等于两次,比较图形验证码是否正确
            if (jpgCode == null || redis_JPGCode == null || !jpgCode.equals(redis_JPGCode)) {
                return R.error("图形验证码输入错误");
            }
        }
        //调用阿里云短信服务
        //模板Code
        String templateCode = SMSUtils.VALIDATE_CODE;
        try {
            SMSUtils.sendShortMessage(templateCode, telephone, validateCode);
            //发送成功保存验证码到redis中,设置过期时间5min
            String key = telephone + RedisMessageConstant.SENDTYPE_REG;
            redisUtils.set(key, validateCode, 300);
            //记录发送的次数
            if (val_count == null) {
                Integer count=1;
                redisUtils.set(key_Count, count, 60 * 60);
                return R.okData(count);
            } else {
                int count = Integer.parseInt(val_count);
                count++;
                redisUtils.set(key_Count, count, 60 * 60);
                return R.okData(count);
            }
        } catch (ClientException e) {
            return R.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "验证码发送失败");
        } catch (Throwable throwable) {
            return R.error(20000, "短信发送失败");
        }
    }

    /**
     * 获取图片验证码
     *
     * @param response
     * @param telephone
     * @throws IOException
     */
    @GetMapping("pc/sandsms/captcha.jpg/{telephone}")
    public void captcha(HttpServletResponse response, @PathVariable String telephone) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(telephone);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }
}
